import os
from celery import Celery
import requests
from eatfun_backend import settings
from celery import shared_task

# 获取当前文件夹名，即为该 Django 的项目名
project_name = os.path.split(os.path.abspath('.'))[-1]
project_settings = '%s.settings' % project_name

# 设置环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', project_settings)

# 实例化 Celery
app = Celery(project_name)
app.config_from_object('django.conf:settings')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()


@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    sender.add_periodic_task(5400, gettokentask.s(), name='gettokentask')

def getaccesstoken():
    params = {
        'appid': settings.appid,
        'secret': settings.appsecret,
        'grant_type': 'client_credential'
    }
    result_dict = requests.get(settings.getAccessToken, params=params).json()
    access_token = result_dict['access_token']
    expires_in = result_dict['expires_in']
    return access_token, expires_in


@app.task
def gettokentask():
    access_token, expires_in = getaccesstoken()
    return access_token
